<template>
  <Top-Page class="open-live">
    <NavBar title="开直播" left-arrow @click-left="navBack()" />

    <view class="field-list">
      <view class="field">
        <view class="field-label">房间号</view>
        <input disabled class="field-value" type="text" v-model="channelId" />
      </view>

      <view class="field">
        <view class="field-label">房间名字</view>
        <input class="field-value" type="text" placeholder="请填写主持人姓名" v-model="roomName" />
      </view>

      <view class="field">
        <view class="field-label">主持人</view>
        <input class="field-value" type="text" placeholder="请填写主持人姓名" v-model="realname" />
      </view>

      <view class="field">
        <view class="field-label">主题</view>
        <input class="field-value" type="text" placeholder="请填写主题吸引观众" v-model="theme" />
      </view>

      <view class="field">
        <view class="field-label">简介</view>
        <input class="field-value" type="text" placeholder="请填写直播介绍" v-model="desc" />
      </view>
    </view>

    <view class="release__imgs">
      <view class="release__imgs-title">上传封面</view>
      <view class="works-item" v-for="(item, index) in files">
        <image class="works-item__image" :src="item.path" mode="aspectFill" @click="handlePreviewImage(index)" />

        <view @click="handleRemoveFile(index)" class="close-css_icon"></view>
      </view>

      <!-- 选择图片 -->
      <view class="cross-css_icon add-image" v-show="files.length < 1" @click="handleChooseFiles"></view>
    </view>

    <view class="begin" @click="begin">立即开播</view>
  </Top-Page>
</template>

<script>
// #ifdef APP
var liveModule = uni.requireNativePlugin('PLV-LiveUniPlugin-StreamerLiveModule');
var configModule = uni.requireNativePlugin('PLV-LiveUniPlugin-StreamerConfigModule');
// #endif
import NavBar from '@/components/NavBar/NavBar.vue';
import { navBack } from '@/utils/utils.js';
import { chooseFilesImg, removeFile, uploadFiles, previewImage } from '@/utils/fileUtils.js';

export default {
  data() {
    return {
      navBack,
      files: [],
      channelId: '123',
      realname: '',
      introduction: '',
      theme: '',
      desc: ''
    };
  },
  components: { NavBar },
  created() {
    this.firstApi();
  },
  methods: {
    // 处理选择文件
    async handleChooseFiles() {
      try {
        this.files = await chooseFilesImg(this.files);
        console.log(this.files, 'this.files');
      } catch (error) {
        console.error('选择文件失败:', error);
      }
    },
    // 处理删除文件
    handleRemoveFile(index) {
      this.files = removeFile(this.files, index);
    },
    // 处理上传文件
    async handleUploadFiles() {
      try {
        const uploadUrl = this.$api.msgApi.uploadImage; // 替换为你的上传接口地址
        const responses = await uploadFiles(this.files, uploadUrl);
        // console.log('上传成功:', responses);
        return responses;
      } catch (error) {
        // console.error('上传失败:', error);
        uni.showToast({
          title: `${error}`,
          icon: 'none'
        });
        return '';
      }
    },
    // 处理图片预览
    handlePreviewImage(index) {
      previewImage(this.files, index);
    },
    async begin() {
      if (!this.roomName) {
        uni.showToast({
          title: '请填写房间名',
          icon: 'none'
        });

        return;
      }

      if (!this.realname) {
        uni.showToast({
          title: '请填写主持人姓名',
          icon: 'none'
        });

        return;
      }

      if (!this.desc) {
        uni.showToast({
          title: '请填写直播介绍',
          icon: 'none'
        });

        return;
      }

      if (!this.roomName) {
        uni.showToast({
          title: '请填写房间名',
          icon: 'none'
        });

        return;
      }

      if (!this.files.length) {
        uni.showToast({
          title: '请上传直播封面图',
          icon: 'none'
        });

        return;
      }

      uni.showToast({
        title: '开播中...',
        icon: 'loading',
        mask: true,
        duration: 999999
      });

      //发表的图片
      const responses = await this.handleUploadFiles();
      let status = true;
      let msg = '';

      const files = [];

      responses.forEach((item) => {
        const data = JSON.parse(item.data);
        if (data.code != 0) {
          status = false;
          msg = data.msg;
        }

        files.push(data.data);
      });

      const userInfo = uni.getStorageSync('userInfo');

      this.$api.msgApi
        .liveOpen({
          type: 2,
          name: this.roomName,
          publisher: this.realname,
          cover_img: files.join(),
          desc: this.desc,
          avatar: userInfo.avatar ?? ''
        })
        .then((res) => {
          uni.hideToast();

          const { channel_id, channel_passwd, live_open } = res.data;

          if (!live_open || live_open == 0) {
            uni.showToast({
              title: '您没有开播权限',
              icon: 'none'
            });
            return;
          }

          //登录SDK
          liveModule.loginStreamer(
            {
              channelId: channel_id,
              password: channel_passwd,
              nickname: this.realname
            },
            (result) => {
              uni.hideToast();

              !result.isSuccess &&
                uni.showToast({
                  title: result.errMsg,
                  icon: 'none'
                });
            }
          );
        });
    },
    firstApi() {
      console.log('firstApi');
    }
  }
};
</script>

<style lang="scss" scoped>
@import './index.scss';
</style>
